package com.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.config.GuliException;
import com.edu.entity.UcenterMember;
import com.edu.mapper.UcenterMemberMapper;
import com.edu.service.UcenterMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.utils.JwtUtils;
import com.edu.utils.MD5;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author mxs
 * @since 2021-11-11
 */
@Service
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {

    @Override
    public String login(UcenterMember member) {
        String mobile = member.getMobile();
        String password = member.getPassword();
        //判断密码或者用户名是否为空
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
            //如果密码或者用户名为空就返回null
            throw new GuliException(20001,"用户名或者密码为空");
        }
        //判断该手机是否存在
        QueryWrapper<UcenterMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        UcenterMember ucenterMember = baseMapper.selectOne(queryWrapper);
        if (ucenterMember == null) {
            //没有这个手机号
            throw new GuliException(20001,"没有这个手机号码");
        }
        //校验密码是否正确
        if (!MD5.encrypt(password).equals(ucenterMember.getPassword())) {
            //密码错误
            throw new GuliException(20001,"密码错误");
        }
        //验证该账户是否为空
        if (ucenterMember.getIsDeleted()){
            //被禁用
            throw  new GuliException(20001,"账户被禁用");
        }
        //根据id和名称生成token
        String jwtToken = JwtUtils.getJwtToken(ucenterMember.getId(), ucenterMember.getNickname());
        //返回token
        return jwtToken;


    }

    @Override
    public UcenterMember getMemberByOpenId(String openId) {
        QueryWrapper<UcenterMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid",openId);
        UcenterMember member = baseMapper.selectOne(queryWrapper);
        return member;
    }
}
